<?php
/**
 *
 *
 *
 */
class Yz_Form_Element_ForeignKey
    extends Yz_Form_Element_Input
{

    public function render(Yz_Template_Interface $template)
    {
        $options = $this->renderOptions($template);
        $o = <<<html
            <select name="{$this->name}">
{$options}
            </select>\n
html;
        return $o;
    }


    /** validate input
     *
     */
    protected function validateType($input)
    {
        $value = parent::validateType($input); // return string or null for empty string
        if (null !== $value and ! ctype_digit($value)) {
            // a form element (SELECT) generated by this class can not produce
            // non-integer values, so the form is likely forged
            // NOTE: subclasses may define some conditions which allow other values
            //      e.g. "any element"=-1 or "use default element"=-2 in addition to "not selected"={ 0 | "" }
            throw Yz_Form_Error_InvalidFormError::_new_();
        }
        if ("0" === $value) { // "not selected", both 0 and "" (empty string)
            $value = null;
        } else {
            try {
                $value = $this->field->getModel()->getItems()->offsetGet($value);
            } catch (NotFoundError $ex) {
                throw Yz_Form_Element_Error_ValueError::_new_();
            }
        }
        return $value;
    }

    /**
     *
     *
     */
    protected function loadOptions()
    {
        debug();
        $field = $this->field;
        $model = $field->getModel();
        try {
            $options = $model->getItems()->all();
        } catch (NotFoundError $ex) {
            $options = array();
        }
        return $options;
    }

    /**
     *
     *
     */
    protected function renderOptions(Yz_Template_Interface $template)
    {
        debug();
        $o = "";
        $currentValue = $this->value ? $this->value->id : 0;
        if (! $this->field->notnull) {
            $selected = $currentValue === 0 ? ' selected="selected"' : '';
            $text = $template->translate("-- Not selected --");
            $o .= <<<html
                    <option{$selected} value="0">{$text}</option>\n
html;
        }
        $options = $this->loadOptions();
        foreach ($options as $option) {
            $text = htmlspecialchars($option->title);
            $selected = $currentValue === $option->id ? ' selected="selected"' : '';
            $o .= <<<html
                    <option{$selected} value="{$option->id}">{$text}</option>\n
html;
        }
        return $o;
    }

}
